package com.htjx.mall.services;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.TransactionStatus;
import org.springframework.transaction.support.TransactionCallbackWithoutResult;
import org.springframework.transaction.support.TransactionTemplate;

import com.htjx.mall.commons.mappers.OrderMapper;
import com.htjx.mall.commons.models.Order;
import com.htjx.mall.commons.utils.page.Page;
import com.htjx.mall.controllers.vo.OrderQuery;

@Service
public class OrderService {
	@Autowired
	private OrderMapper orderMapper;
	@Autowired
	private TransactionTemplate transactionTemplate;
	
	
	public List<Order> selectOrder(List<Long> orderIds) {
		return orderMapper.selectBatch(orderIds);
	}
	
	public Order selectOne(long id) {
		List<Long> orderIds = new ArrayList<Long>();
		orderIds.add(id);
		
		List<Order> orderList = orderMapper.selectBatch(orderIds);
		if(orderList == null) {
			return null;
		}
		
		if(orderList.size() != 1) {
			return null;
		}
		
		return orderList.get(0);
	}
	
	public void updateOne(final Order order) {
		transactionTemplate.execute(new TransactionCallbackWithoutResult() {
			@Override
			protected void doInTransactionWithoutResult(TransactionStatus status) {
				orderMapper.updateOne(order);
			}
		});
	}
	
	public void deleteOne(final long id) {
		transactionTemplate.execute(new TransactionCallbackWithoutResult() {
			@Override
			protected void doInTransactionWithoutResult(TransactionStatus status) {
				orderMapper.deleteOne(id);
			}
		});
	}
	
	public Page<Order> page(OrderQuery orderQuery, Page<Order> page) {
		Map<String, Object> params = new HashMap<String, Object>();
		params.put("offset", page.getFirst() - 1);
		params.put("size", page.getPageSize());
		params.put("orderQuery", orderQuery);
		List<Order> result = orderMapper.page(params);
		page.setResult(result);
		if (page.isAutoCount()) {
			int totalCount = orderMapper.pageCount(params);
			page.setTotalCount(totalCount);
		}
		
		return page;
	}
}
